package com.waimai1.waimai.controller;

import com.alibaba.excel.EasyExcel;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.waimai1.waimai.common.*;
import com.waimai1.waimai.dao.ChoujiangWhiteDao;
import com.waimai1.waimai.dto.CouponPersonWhiteDto;
import com.waimai1.waimai.entity.ChoujiangWhite;
import com.waimai1.waimai.exception.EnumException;
import com.waimai1.waimai.exception.NotErrorException;
import com.waimai1.waimai.service.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.UUID;
@CrossOrigin(origins = "*")
@RestController
@RequestMapping(value = "/local",method = RequestMethod.POST)
@Slf4j
//@MultipartConfig(maxFileSize = 1024)
public class UploadFile {
    @Value("${oss.endpoint}")
    private String  endpoint;
    @Value("${oss.accessKeyId}")
    private String accessKeyId;
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${oss.bucketName}")
    private String bucketName;
    @Autowired
    private ChoujiangService choujiangService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private CouponPersonService couponPersonService;
    @Autowired
    private QuanyiPersonService quanyiPersonService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 实现上传图片到OSS
     */
    @PostMapping("/ossUpload")
    public R<String> ossUpload(@RequestBody MultipartFile file) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        // 上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try{
            String url =  "chongxie/"+fileName;
            ossClient.putObject(bucketName,url, inputStream);// 文件访问路径

            return R.success(url);// 把上传到oss的路径返回

        }catch (Exception err){
            throw new NotErrorException(1008,"上传失败");
        }
        finally {
            // 关闭ossClient
            ossClient.shutdown();
        }
    }

    @PostMapping(value = "/upload", headers = "content-type=multipart/form-data")
    public R<String> upload(@RequestParam("file") MultipartFile file,
                            HttpServletRequest request) throws IOException {
        //文件为空返回
        if (file.isEmpty()){
            throw new NotErrorException(EnumException.NULL_FILE);
        }
        //文件不为空判断是否是图片
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        //设置允许上传文件类型
        String suffixList = "jpg,png,ico,bmp,jpeg";
        if (!suffixList.contains(suffix)) {
            throw new NotErrorException(EnumException.NOT_IMAGE);
        }
        String filename1 =BaseContext.getAcid()+ String.valueOf(new Date().getTime()).substring(5)+file.getOriginalFilename();//生成唯一图片路径
            try {
                //使用绝对地址
                File filepath = new File("imgs");
                if (!filepath.exists()) {
                    filepath.mkdirs();
                }
                Path parentPath = Paths.get(filepath.getCanonicalPath());
                // 文件保存路径
                Path fullPath = parentPath.resolve(filename1);
                // 转存文件
                file.transferTo(new File(fullPath.toString()));
                String url =filename1;
                return R.success(url);
            } catch (Exception e) {
                e.printStackTrace();
                throw new IOException();
            }
    }
    @PostMapping("uploadExcel")
    @ResponseBody
    public R<Long> uploadExcel(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), ChoujiangWhite.class, new ExcelListener(choujiangService)).sheet().doRead();
        return R.success(redisTemplate.opsForSet().size(BaseContext.getAcid()+":choujiangWhite"));
    }
    @PostMapping("uploadQuanyiExcel")
    @ResponseBody
    public R<Long> uploadQuanyiExcel(MultipartFile file,String sort) throws IOException {
        BaseContext.setSort(sort);
//        借用CouponPersonWhiteDto，一样的
        EasyExcel.read(file.getInputStream(), CouponPersonWhiteDto.class, new QuanyiExcelListener(quanyiPersonService)).sheet().doRead();
        return R.success(redisTemplate.opsForSet().size(BaseContext.getAcid()+":quanyiWhite"+sort));
    }
    //上传couponperson白名单
    @PostMapping("uploadCouponExcel")
    @ResponseBody
    public R<Long> uploadCouponExcel(MultipartFile file,String wexinNo) throws IOException {
        BaseContext.setWexinNo(wexinNo);
        EasyExcel.read(file.getInputStream(), CouponPersonWhiteDto.class, new CouponExcelListener(couponPersonService)).sheet().doRead();
        return R.success(redisTemplate.opsForSet().size(BaseContext.getAcid()+":couponPersonWhite"+wexinNo));
    }
    @GetMapping("clearChoujiangWhite")
    public R<String> clearChoujiangWhite(){
        choujiangService.clearExcelRedis();
        return R.success("ok");
    }
    @GetMapping("clearCouponWhite/{wexinNo}")
    public R<String> clearCouponWhite(@PathVariable String wexinNo){
        couponService.clearCouponWhiteRedis(wexinNo);
        return R.success("ok");
    }
    @GetMapping("clearQuanyiWhite/{sort}")
    public R<String> clearQuanyiWhite(@PathVariable String sort){
        quanyiPersonService.clearQuanyiWhiteRedis(sort);
        return R.success("ok");
    }
}
